package com.app.scale.set;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import com.app.scale.R;
import com.app.scale.basis.BasisActivity;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.vandin.weigher.sdk.connector.IWeigh;
import com.vandin.weigher.sdk.connector.IWeighCallback;
import com.vandin.weigher.sdk.connector.WeightData;
import com.vandin.weigher.sdk.weigher.WeightSerialPort;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android_serialport_api.SerialPortFinder;
import butterknife.BindView;
import butterknife.OnClick;
import my.MySharedPreferences;

/***
 * 秤参数
 * **/
public class ScaleSetActivity extends BasisActivity implements IWeighCallback {

    private IWeigh IControl;


    @BindView(R.id.tv_connectResult)
    TextView tv_connectResult;
    @BindView(R.id.tv_weight)
    TextView tv_weight;

    @BindView(R.id.sp_port)
    MaterialSpinner spSerialPort;
    @BindView(R.id.sp_baudrate)
    MaterialSpinner spBaudrate;

    private String[] baudrates;//波特率
    private String[] ports;//端口号
    private String selectPort;//选中端口号
    private int selectBaudrate;//选中波特率

    private  SerialPortFinder mSerialPortFinder;
    MySharedPreferences mSp;

    @Override
    public void initViews() {
        // TODO Auto-generated method stub
        super.initViews();
        setContentView(R.layout.scale_set_activity);
        setTitle("电子秤参数设置");

        setTitleLeftButton(R.drawable.ic_arrow_back, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mSp = new MySharedPreferences(this);
        setTitleBg(R.color.base_blue);

    }

    @Override
    public void initData(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.initData(savedInstanceState);
        try {
            ports = getSrialPortList();
            if (ports != null&&ports.length>0) {
                ports = duplicateRemoval(ports);//数组去重
                Arrays.sort(ports);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        spSerialPort.setItems(ports);
        spSerialPort.setSelectedIndex(mSp.getPortIndex());
        spSerialPort.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
               selectPort = item;
               mSp.putPort(item);
               mSp.putPortIndex(position);
            }
        });

        spBaudrate.setItems(getResources().getStringArray(R.array.baudrate));
        spBaudrate.setSelectedIndex(mSp.getBaudrateIndex());
        spBaudrate.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                selectBaudrate = Integer.valueOf(item);
                mSp.putBaudrate(Integer.valueOf(item));
                mSp.putBaudrateIndex(position);
            }
        });


    }








    @OnClick(R.id.ButTest)
    public void ButTestBtn(){
        if (IControl != null) {
            IControl.disconnect();
        }
        WeightData weightData = new WeightData();
        weightData.setPort(selectPort);
        weightData.setBaudrate(selectBaudrate);
        IControl = new WeightSerialPort(this, this, weightData);
        IControl.OpenScaleUart();
    }

    @OnClick(R.id.ButBreak)
    public void butBreakBtn(){
        //断开连接
        if (IControl != null) {
            IControl.disconnect();
            tv_weight.setText("未获取重量");
        } else {
            showToast("请先初始化！");
        }
    }

    @OnClick(R.id.startRead)
    public void startReadBtn(){
        if (IControl != null) {
            IControl.GetWeight();
        } else {
            showToast("请先初始化！");
        }
    }

    @OnClick(R.id.stopRead)
    public void stopReadBtn(){
        if (IControl != null) {
            IControl.StopRead();
        } else {
            showToast("请先初始化！");
        }
    }

    @OnClick(R.id.btnSerialZero)
    public void zeroBtn(){
        if (IControl != null) {
            IControl.SetZero();
        } else {
            showToast("请先初始化！");
        }
    }










    //获取设备端口号
    public String[] getSrialPortList() {
        mSerialPortFinder = new SerialPortFinder();
        //ports =
        //String[] entriesReturn = new String[ports.length];
        /*for (int i = 0; i < ports.length; i++) {
            entriesReturn[i] = ports[i].substring(0, 5);
        }*/
        return mSerialPortFinder.getAllDevices();
    }

    //数组去重
    public static String[] duplicateRemoval(String[] arrStr) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < arrStr.length; i++) {
            if (!list.contains(arrStr[i])) {
                list.add(arrStr[i]);
            }
        }
        //返回一个包含所有对象的指定类型的数组
        String[] newArrStr = list.toArray(new String[1]);
        return newArrStr;
    }


    @Override
    public void onConnect(int index,final String str, final boolean is) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                tv_connectResult.setText(java.lang.String.format("%d----%s", index,str));
            }
        });
    }

    @Override
    public void onReceiveData(final String frame,final String weight, final boolean isSta) {
        if (isFinishing()) {
            return;
        }
        runOnUiThread(new Runnable() {   //执行UI更新
            @Override
            public void run() {
                if (isSta) {
                    try {
                        tv_weight.setText(java.lang.String.format("稳定：%skg", weight));
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                    }
                } else {
                    try {
                        tv_weight.setText(java.lang.String.format("未稳定：%skg", weight));
                    } catch (Throwable throwable) {
                        throwable.printStackTrace();
                    }
                }
            }
        });
    }
}
